package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    //添加购物车
    @Override
    public Cart add(Cart cart) {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, UserHolder.get().getId())
                .eq(cart.getDishId() != null, Cart::getDishId, cart.getDishId())
                .eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId());
        Cart carFromDb = cartMapper.selectOne(queryWrapper);
        if (carFromDb != null) {
            carFromDb.setNumber(carFromDb.getNumber() + 1);
            cartMapper.updateById(carFromDb);
            return carFromDb;
        } else {
            cart.setUserId(UserHolder.get().getId());
            cart.setNumber(1);
            cart.setCreateTime(new Date());
            cartMapper.insert(cart);
            return cart;
        }

    }
//查询购物车
    @Override
    public List<Cart> findList() {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, UserHolder.get().getId());
        List<Cart> cartList = cartMapper.selectList(queryWrapper);
        return cartList;
    }
    //清空购物车
    @Override
    public void remove() {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, UserHolder.get().getId());
      cartMapper.delete(queryWrapper);
    }
//修改购物车
    @Override
    public Cart sub(Cart cart) {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, UserHolder.get().getId())
                .eq(cart.getDishId() != null, Cart::getDishId, cart.getDishId())
                .eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId());
        Cart carFromDb = cartMapper.selectOne(queryWrapper);
        if (carFromDb!=null) {
           carFromDb.setNumber(carFromDb.getNumber() - 1);
            cartMapper.updateById(carFromDb);
            if (carFromDb.getNumber()<=0) {
                cartMapper.deleteById(carFromDb);
            }
        }
        return cart;
    }


}
